package com.eobard.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.eobard.utils.ResponseUtils;
import com.eobard.utils.Result;
import com.eobard.utils.ResultCode;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Eobard_Thawne
 * @version 1.0
 * @date 2022/8/6 -18:10
 */

/**
 * 认证用户无权限处理器类
 */
@Component
public class AuthAccessDeniedHandler implements AccessDeniedHandler {

    /**
     * 认证用户无权限访问:用户存在但未分配权限
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        //返回登陆失败原因
        String result=JSON.toJSONString(Result.error().code(ResultCode.NO_AUTH).message("无权限访问,请联系管理员！"), SerializerFeature.DisableCircularReferenceDetect);
//        //设置响应编码格式
//        response.setContentType("application/json;charset=utf-8");
//        //获取输出流,并返回前端JSON数据
//        ServletOutputStream outputStream = response.getOutputStream();
//        outputStream.write(result.getBytes(StandardCharsets.UTF_8));
//        outputStream.flush();
//        outputStream.close();

        //通过流对象输出JSON到前端
        ResponseUtils.writeJSON(result,response);
    }
}
